package com.jwm.client.soft;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author 崔洁
 */
@Component
public class NginxConfigEditor {
    private static final Logger logger = LoggerFactory.getLogger(NginxConfigEditor.class);

    public String getNginxConfig(String filePath) {
        logger.info("客户端 -> 获取NginxConfig:{}", filePath);
        filePath += "/conf/nginx.conf";
        String content = "";
        try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
            List<String> updatedLines = lines.collect(Collectors.toList());
            content = String.join("\r\n", updatedLines);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("客户端 -> 获取NginxConfig错误\n{}", e.getMessage());
        }
        logger.info("客户端 -> 获取NginxConfig成功!");
        return content;
    }

    public String editNginxConfig(String filePath, String content) {
        logger.info("客户端 -> 更新NginxConfig:{}\n{}", filePath, content);
        filePath += "/conf/nginx.conf";
        try {
            List<String> updatedLines = new ArrayList<>();
            updatedLines.add(content);
            Files.write(Paths.get(filePath), updatedLines);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("客户端 -> 更新NginxConfig错误\n{}", e.getMessage());
        }
        logger.info("客户端 -> 更新成功");
        return "成功";
    }
}
